<template>
  <div>
    上传你的帅照：<input type="file" @change="handler" accept="image/*">
    <div>
      <h2>预览</h2>
      <img :src="imgSrc" alt="" style="width: 60px;">
    </div>
  </div>
</template>

<script setup>
import axios from 'axios'
import { ref } from 'vue'
const imgSrc = ref('')

const handler = async (event) => {
  // 1.获取上传文件的二进制信息
  const file = event.target.files[0]
  if (!file) {
    alert('请上传文件')
    return
  }

  // 2. 预览图片
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = (event) => {
    // console.log(event.target.result) // base64
    imgSrc.value = event.target.result
  }

  const formData = new FormData()
  formData.set('username', '林加福')
  formData.set('age', '19')
  formData.set('avatar', file)

  // 3.上传给服务器
  let { data } = await axios.post('http://127.0.0.1:3000/upload', formData)
  console.log(data)

}

</script>
